/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * Modelos.java
 *
 * Created on 07-dic-2013, 22:38:56
 */
package maestros;

import core.*;
import java.sql.*;
import java.awt.*;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Oscar Aguilera
 */
public class Modelos extends javax.swing.JInternalFrame {

    int fila = -1;
    private String condiciones, tbls;
    private Object[][] valores;
    private Query cmd;
    private Conexion conn;
    String tablamaster = "tbl_modelo";
    String[] campos = {"id_modelo", "nombre","id_marca","cilindrada","id_tipovehiculo","comentarios"};
    String[] titcols = {"id",        "nombre", "marca","cilindrada","tipo"};
    String nomkey = "id_modelo";
    DefaultTableModel datos;

    String idmarca =null;
    String idtipo=null;
    /** Creates new form Modelos */
    public Modelos() {
        initComponents();

        Dimension pantalla = Toolkit.getDefaultToolkit().getScreenSize();


        int height = pantalla.height;
        int width = pantalla.width;
        setSize(550, height);



        combomarcas();
        combotipos();

        btnNuevo.setEnabled(false);
        btnBorrar.setEnabled(false);
        limpiar();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        lblNombre = new javax.swing.JLabel();
        txtNombre = new javax.swing.JTextField();
        btnBorrar = new javax.swing.JButton();
        btnGrabar = new javax.swing.JButton();
        btnSalir = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        tblRegistros = new javax.swing.JTable();
        jLabel1 = new javax.swing.JLabel();
        txtId = new javax.swing.JTextField();
        btnNuevo = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        cmbMarca = new javax.swing.JComboBox();
        cmbTipoVehiculo = new javax.swing.JComboBox();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        txtCilindrada = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        txtComentarios = new javax.swing.JTextArea();

        lblNombre.setText("Nombre");

        btnBorrar.setText("Borrar");
        btnBorrar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnBorrarActionPerformed(evt);
            }
        });

        btnGrabar.setText("Grabar");
        btnGrabar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGrabarActionPerformed(evt);
            }
        });

        btnSalir.setText("Salir");
        btnSalir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSalirActionPerformed(evt);
            }
        });

        tblRegistros.setFont(new java.awt.Font("Lucida Grande", 0, 14)); // NOI18N
        tblRegistros.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        tblRegistros.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tblRegistrosMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(tblRegistros);

        jLabel1.setText("Codigo");

        txtId.setBackground(new java.awt.Color(217, 217, 217));
        txtId.setEditable(false);
        txtId.setForeground(new java.awt.Color(0, 8, 255));
        txtId.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtIdActionPerformed(evt);
            }
        });

        btnNuevo.setText("Nuevo");
        btnNuevo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNuevoActionPerformed(evt);
            }
        });

        jLabel2.setText("Modelos de Vehiculos");

        jLabel3.setText("Marca");

        cmbMarca.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        cmbMarca.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmbMarcaActionPerformed(evt);
            }
        });

        cmbTipoVehiculo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        jLabel4.setText("Tipo");

        jLabel5.setText("Cilindrada");

        jLabel6.setText("Comentarios");

        txtComentarios.setColumns(20);
        txtComentarios.setRows(5);
        jScrollPane2.setViewportView(txtComentarios);

        org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                    .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(org.jdesktop.layout.GroupLayout.LEADING, jPanel1Layout.createSequentialGroup()
                        .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(lblNombre)
                            .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                                .add(jLabel3)
                                .add(jLabel4)
                                .add(org.jdesktop.layout.GroupLayout.TRAILING, jLabel5))
                            .add(jLabel1))
                        .add(31, 31, 31)
                        .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(jPanel1Layout.createSequentialGroup()
                                .add(btnBorrar)
                                .add(12, 12, 12)
                                .add(btnNuevo)
                                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                                .add(btnGrabar)
                                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                                .add(btnSalir))
                            .add(txtId, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 78, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                            .add(cmbMarca, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                            .add(jPanel1Layout.createSequentialGroup()
                                .add(64, 64, 64)
                                .add(jLabel2))
                            .add(txtNombre, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 348, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                            .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING, false)
                                .add(org.jdesktop.layout.GroupLayout.LEADING, txtCilindrada)
                                .add(org.jdesktop.layout.GroupLayout.LEADING, cmbTipoVehiculo, 0, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
                    .add(org.jdesktop.layout.GroupLayout.LEADING, jPanel1Layout.createSequentialGroup()
                        .add(jLabel6)
                        .add(18, 18, 18)
                        .add(jScrollPane2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 356, Short.MAX_VALUE)))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1Layout.createSequentialGroup()
                .add(20, 20, 20)
                .add(jLabel2)
                .add(18, 18, 18)
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel1)
                    .add(txtId, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel3)
                    .add(cmbMarca, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel4)
                    .add(cmbTipoVehiculo, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel5)
                    .add(txtCilindrada, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 28, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(lblNombre)
                    .add(txtNombre, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jLabel6)
                    .add(jScrollPane2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 73, Short.MAX_VALUE))
                .add(18, 18, 18)
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(btnBorrar)
                    .add(btnGrabar)
                    .add(btnSalir)
                    .add(btnNuevo))
                .add(18, 18, 18)
                .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 157, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .add(jPanel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(91, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void combomarcas() {

        conn = new Conexion();
        cmd = new Query(conn);

        cmbMarca.removeAllItems();

        String[] columnas = {"id_marca", "nombre"};
        condiciones = " 1 ORDER BY nombre asc";
        tbls = "tbl_marca";

        valores = cmd.leeRegistros(columnas, condiciones, tbls);

        for (int i = 0; i < valores.length; i++) {

            cmbMarca.addItem(new EntradaCombo(valores[i][0].toString(),valores[i][1].toString()));
             
        }

        conn.desconectar();
    }

    private void combotipos(){


                conn = new Conexion();
        cmd = new Query(conn);

        cmbTipoVehiculo.removeAllItems();

        String[] columnas = {"id_tipovehiculo", "nombre"};
        condiciones = " 1 ORDER BY nombre asc";
        tbls = "tbl_tipovehiculo";

        valores = cmd.leeRegistros(columnas, condiciones, tbls);

        for (int i = 0; i < valores.length; i++) {

            cmbTipoVehiculo.addItem(new EntradaCombo(valores[i][0].toString(),valores[i][1].toString()));

        }

        conn.desconectar();
    }

    private void btnGrabarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGrabarActionPerformed
        // TODO add your handling code here:

        conn = new Conexion();
        cmd = new Query(conn);
        String id = txtId.getText();
        String nombre = txtNombre.getText();
        String cilindrada = txtCilindrada.getText();
        String comentarios = txtComentarios.getText();

          EntradaCombo item1 = (EntradaCombo) cmbMarca.getSelectedItem();

          try{
           idmarca=item1.getValue();
          } catch (Exception e) {
                  System.out.println("error combo marca: "+cmbMarca.getSelectedItem());
          }



           EntradaCombo item2 = (EntradaCombo)cmbTipoVehiculo.getSelectedItem();

          try{
           idtipo=item2.getValue();
          } catch (Exception e) {
                  System.out.println("error combo tipo vehi: "+cmbTipoVehiculo.getSelectedItem());
          }


        if (id.equals("")) {

            String[] columna = {nomkey};
            condiciones = "nombre='" + nombre + "'";
            if (!cmd.existeCampo(columna, condiciones, tablamaster)) {

                id = "0";
                String values = "'" + id + "','" + nombre + "'"+ ",'"+ idmarca  +"','" +cilindrada+"','"+idtipo+"','"+comentarios+"'";

                String campos = cmd.getNomCols(conn.bd, tablamaster);
                cmd.insertRegistro(tablamaster, campos, values);

            } else {
                System.out.println("ya existe campo, insercion anulada");

            }

        } else {
            // actualiza datos
            String values ;
            values= "nombre='" + nombre+ "',id_marca='"+idmarca+"',"
                        +"id_tipovehiculo='"+idtipo+"',"
                        +"cilindrada='"+cilindrada+"',"
                        +"comentarios='"+comentarios+"'";
            cmd.actualizaRegistro(tablamaster, values, nomkey + "=" + id);

        }
        conn.desconectar();

        limpiar();
    }//GEN-LAST:event_btnGrabarActionPerformed

    private void llenaTabla() {


        conn = new Conexion();
        cmd = new Query(conn);

        condiciones = " t1.id_marca=t2.id_marca and  t1.id_tipovehiculo=t3.id_tipovehiculo";
        String[] columnas = {"t1.id_modelo", "t1.nombre", "t2.nombre","t1.cilindrada","t3.nombre"};
        String tablas = tablamaster + " t1, tbl_marca t2, tbl_tipovehiculo t3";
       
        valores = cmd.leeRegistros(columnas, condiciones, tablas);
        datos = new DefaultTableModel(valores, titcols);
        tblRegistros.setModel(datos);
        
        conn.desconectar();

    }

    private void limpiar() {
        txtId.setText("");
        txtNombre.setText("");
        txtCilindrada.setText("");
        txtComentarios.setText("");
        cmbMarca.setSelectedIndex(0);
        cmbTipoVehiculo.setSelectedIndex(0);
        btnNuevo.setEnabled(false);
        btnBorrar.setEnabled(false);
        llenaTabla();
    }

    private void btnSalirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSalirActionPerformed
        this.dispose();
}//GEN-LAST:event_btnSalirActionPerformed

    private void tblRegistrosMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tblRegistrosMouseClicked
        String marca=null;
        String tipovehiculo=null;

        conn = new Conexion();
        cmd = new Query(conn);

        condiciones = " 1 ";

       
       // return valores[0][0].toString() + " ::: " + valores[0][1].toString();

        fila = tblRegistros.rowAtPoint(evt.getPoint());
        if (fila > -1) {
            txtId.setText(String.valueOf(datos.getValueAt(fila, 0)));

            valores = cmd.leeRegistros(campos, nomkey+"=" +  String.valueOf(datos.getValueAt(fila, 0)) , tablamaster);
            txtNombre.setText(valores[0][1].toString());
            txtCilindrada.setText(valores[0][3].toString());
            txtComentarios.setText(valores[0][5].toString());
            marca=String.valueOf(datos.getValueAt(fila,2));
            tipovehiculo=String.valueOf(datos.getValueAt(fila,4));
           
            
        }

         for (int i = 0; i < cmbMarca.getItemCount(); i++)
            {

                  System.out.println(marca+" <-> "+cmbMarca.getItemAt(i).toString());
                   if(marca.equals(cmbMarca.getItemAt(i).toString())){
                       cmbMarca.setSelectedIndex(i);
                       break;
                   }


            }




            for (int i = 0; i < cmbTipoVehiculo.getItemCount(); i++)
            {
                   System.out.println(idtipo+" <-> "+cmbTipoVehiculo.getItemAt(i).toString());
                   if(tipovehiculo.equals(cmbTipoVehiculo.getItemAt(i).toString())){
                       cmbTipoVehiculo.setSelectedIndex(i);
                       break;
                   }


            }



        btnNuevo.setEnabled(true);
        btnBorrar.setEnabled(true);
     
        conn.desconectar();

    }//GEN-LAST:event_tblRegistrosMouseClicked

    private void txtIdActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtIdActionPerformed
        // TODO add your handling code here:
}//GEN-LAST:event_txtIdActionPerformed

    private void btnNuevoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNuevoActionPerformed
        // TODO add your handling code here:
        limpiar();
}//GEN-LAST:event_btnNuevoActionPerformed

    private void cmbMarcaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmbMarcaActionPerformed

      EntradaCombo item = (EntradaCombo)cmbMarca.getSelectedItem();

      try{
     // System.out.println("ID marca:"+item.getValue());
      } catch (Exception e) {
              System.out.println("error combo marca: "+cmbMarca.getSelectedItem());
      }
      
    }//GEN-LAST:event_cmbMarcaActionPerformed

    private void btnBorrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBorrarActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_btnBorrarActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnBorrar;
    private javax.swing.JButton btnGrabar;
    private javax.swing.JButton btnNuevo;
    private javax.swing.JButton btnSalir;
    private javax.swing.JComboBox cmbMarca;
    private javax.swing.JComboBox cmbTipoVehiculo;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JLabel lblNombre;
    private javax.swing.JTable tblRegistros;
    private javax.swing.JTextField txtCilindrada;
    private javax.swing.JTextArea txtComentarios;
    private javax.swing.JTextField txtId;
    private javax.swing.JTextField txtNombre;
    // End of variables declaration//GEN-END:variables
}
